﻿using System.Collections.Specialized;
using System.Configuration;
using System.Web.Security;

namespace Heroius.ArtechWCF.Server
{
    public class RemoteRoleProvider : RoleProvider
    {
        public OperationInvoker<IRoleService> Proxy { get; private set; }
        public virtual string EndpointName { get; set; }

        public override void Initialize(string name, NameValueCollection config)
        {
            base.Initialize(name, config);
            this.EndpointName = config["endpoint"];
            if (null == this.EndpointName)
            {
                throw new ConfigurationErrorsException("缺少必须配置属性\"endpoint\"");
            }
            this.Proxy = new OperationInvoker<IRoleService>(this.EndpointName);

            var providerData = Proxy.Invoke(proxy => proxy.GetProviderData());
            ApplicationName = providerData.ApplicationName;
        }

        public override string ApplicationName { get; set; }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            Proxy.Invoke(proxy => proxy.AddUsersToRoles(usernames, roleNames));
        }

        public override void CreateRole(string roleName)
        {
            Proxy.Invoke(proxy => proxy.CreateRole(roleName));
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            return Proxy.Invoke(proxy => proxy.DeleteRole(roleName, throwOnPopulatedRole));
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            return Proxy.Invoke(proxy => proxy.FindUsersInRole(roleName, usernameToMatch));
        }

        public override string[] GetAllRoles()
        {
            return Proxy.Invoke(proxy => proxy.GetAllRoles());
        }

        public override string[] GetRolesForUser(string username)
        {
            return Proxy.Invoke(proxy => proxy.GetRolesForUser(username));
        }

        public override string[] GetUsersInRole(string roleName)
        {
            return Proxy.Invoke(proxy => proxy.GetUsersInRole(roleName));
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            return Proxy.Invoke(proxy => proxy.IsUserInRole(username, roleName));
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            Proxy.Invoke(proxy => proxy.RemoveUsersFromRoles(usernames, roleNames));
        }

        public override bool RoleExists(string roleName)
        {
            return Proxy.Invoke(proxy => proxy.RoleExists(roleName));
        }
    }
}
